package com.example.musicgui.controller;

import com.example.musicgui.client.MusicClient;
import com.example.musicgui.model.Music;
import com.example.musicgui.model.ResponseBodyMessage;
import com.example.musicgui.tools.ObjuctOrJSON;
import com.fasterxml.jackson.core.JsonProcessingException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MusicController {
    private ObjuctOrJSON<String> json = new ObjuctOrJSON<>();
    public List<Music> getMusic() throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("type","allmusic");
        String getmusic = json.toJSON(map);
        ResponseBodyMessage<String> result = json.result(new MusicClient().start(getmusic));
        List<Music> list = musicToList(result.getData());
        return list;
    }
    private List<Music> musicToList(String data) {
        List<Music> musicList = new ArrayList<>();
        data = data.substring(1,data.length()-1);
        String[] oneMusic = data.split("#, ");
        for (String music:oneMusic) {
            Map<String,String> map = new HashMap<>();
            String[] musicMessage = music.split(",");
            for (String message:musicMessage) {
                String[] one = message.split(":");
                if ("count".equals(one[0])){
                    one[1] = one[1].replace("#", "").trim();
                }
                map.put(one[0],one[1]);
            }
            Music sing = new Music(map.get("title"),map.get("time"),map.get("url"),map.get("singer"),Integer.valueOf(map.get("count")));
            musicList.add(sing);
        }
        return musicList;
    }
}
